package com.xln.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xln.pojo.Admin;
import com.xln.service.AdminService;
import com.xln.util.PassEncrypt;
import com.xln.util.ResEnum;
import com.xln.util.Result;
import com.xln.util.Token;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@Slf4j
public class Login {
//    @RequestMapping(value = {"/","/xlnBlog", "/login"})
//    public String manageLogin(){
//
//        return "login";
//    }
    @Resource
    AdminService adminService;

    @RequestMapping(value = {"/login"})
    public String userLogin(){

        return "login";
    }

    @ResponseBody
    @RequestMapping(value = {"/loginManage"})
    public Result loginManage(Admin admin, Model model, HttpServletResponse response){
        String username = admin.getUsername();
        String password = admin.getPassword();
        log.info("用户名：{}",username);
        log.info("密码：{}",password);
        Admin dbAdmin = adminService.getOne(new QueryWrapper<Admin>().eq("username", username));
        log.info("数据库用户：{}",dbAdmin);
        if (dbAdmin == null){
//            model.addAttribute("loginError",ResEnum.USER_NOT_EXIST);
            return Result.success(ResEnum.USER_NOT_EXIST);
        }
        if (!dbAdmin.getPassword().equals(PassEncrypt.md5WithSalt(admin.getPassword()))){

//            model.addAttribute("loginError",ResEnum.PASSWORD_ERROR);
            return Result.success(ResEnum.PASSWORD_ERROR);
        }

        String token = Token.createToken(dbAdmin.getUsername(), dbAdmin.getPassword());
//        response.setHeader("Authorization",token);
        log.info("token:{}",token);
//        model.addAttribute("admin", Result.success(ResEnum.LOGIN_SUCCESS,dbAdmin));
        response.addCookie(new Cookie("Authorization",token));
        return Result.success(ResEnum.LOGIN_SUCCESS, token);
    }
}
